<?php
require "../../../../framework/bootstrap.inc.php";
require "Config.php";
require "OAuth_Client.php";
require "util.php";
require "RpcClient.php";
require "RpcService.php";
require "UserService.php";
$isseting=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_systemsetting')." order by id asc limit 1");
$app_key = $isseting["elem_key"];
$app_secret = $isseting["elem_secret"];
$sandbox = $isseting['elemdebug'] ? true : false;
$scope = "all";
$config = new Config($app_key, $app_secret, $sandbox);
$callback_url = $_W['siteroot']."callback.php";

if($_GET["shopid"] && $_GET["weid"]){
    isetcookie("m_shopid",$_GET["shopid"]);
    isetcookie("m_uniacid",$_GET["weid"]);
    header("location:https://open-api-sandbox.shop.ele.me/qrauthorize?code=fa0c937400e60ba2ae54f03ca62ecbb1");
    die();
}
$content = file_get_contents("php://input");
$code = $_GET["code"];
$error = $_GET["error"];

//判断错误的情形
if ($error != null) {
    echo $_GET["error"];
    echo "<br>";
    echo $_GET["error_description"];
    return;
}
if ($code == null) {

    return;
}
$token='';
try {
    $client=new OAuth_Client($config);
    $token = $client->get_token_by_code($code, $callback_url);
} catch (Exception $e) {
    die("获取token失败");
    return;
}
$user_service = new UserService($token, $config);
$user = $user_service->get_user();
$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_elemtoken')." where userid=:a",array(":a"=>$user->userId));
$shopname="";
foreach ($user->authorizedShops as $shop) {
    $shop2=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_elemtoken')." where shopid=:b",array(":b"=>$shop->id));
    if($shop2)continue;
    $shopname=$shop->id;
    $data=array(
        "weid"=>$_GPC['m_uniacid'],
        "groupid"=>$_GPC['m_shopid'],
        "userid"=>$user->userId,
        "access_token"=>$token->access_token,
        "token_type"=>$token->token_type,
        "expires_in"=>($token->expires_in)+TIMESTAMP,
        "refresh_token"=>$token->refresh_token,
        "scope"=>$token->scope,
        "shopid"=>$shop->id,
        "title"=>$shop->name,
    );
    pdo_insert('j_hmoney_elemtoken',$data);
}
die("授权成功,请关闭页面。");
